<template>
  <VueDraggable
    ref="el"
    v-model="volunteerInfos"
    :animation="150"
    ghostClass="ghost"
    class="flex-col gap-2 p-4 w-300px h-300px m-auto bg-gray-500/5 rounded"
    @end="draggableEnd"
  >
    <div
      class="schoolList"
      v-for="(data, index) in volunteerInfos"
      :key="data.id"
    >
      <div class="flex">
        <div class="schoolList-sequence">
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-button link style="font-size: 17px; color: #333"
                >{{ data.key }}
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  size="large"
                  v-for="(keyStr, idx) in keys"
                  @click="onClickVolunteerInfoKeysItem(index, idx)"
                  command="a"
                >
                  {{ keyStr }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="schoolList-Left">
          <!-- <h1 v-show="showChancelv">{{ data.collegeData?.chance }}%</h1> -->
          <div v-if="data.collegeData.isNewly">
            <h1 style="font-size: 24px">新增</h1>
          </div>
          <div v-else>
            <span v-show="showChancelv"
              ><span class="schoolList-Left-chance">{{
                data.collegeData?.chance
              }}</span
              >%</span
            >
            <div class="schoolList-Left-size">
              {{ data.collegeData?.probabilityExplain }}
            </div>
          </div>

          <div
            :class="
              data.collegeData?.chance_lv == 1
                ? 'chance1'
                : data.collegeData?.chance_lv == 2
                  ? 'chance2'
                  : 'chance3'
            "
            class="schoolList-Left-number"
          >
            {{
              data.collegeData?.chance_lv == 1
                ? '冲'
                : data.collegeData?.chance_lv == 2
                  ? '稳'
                  : '保'
            }}
          </div>
        </div>
        <div
          class="schoolList-Center curr"
          style="flex: 1 1 0%"
          @click="handleScoolNameClick(data)"
        >
          <div class="schoolName">{{ data.collegeData?.collegeName }}</div>
          <div class="schoolList-size">
            <p>
              代码: {{ data?.collegeData?.collegeEnrollCode }} |
              {{ data?.collegeData?.features.join(' / ') }} |
              {{
                data?.collegeData?.provinceName +
                ' ' +
                data?.collegeData?.cityName +
                ' / ' +
                data?.collegeData?.categories.join(' / ') +
                ' / ' +
                data?.collegeData?.natureType +
                ' / ' +
                '排名' +
                (data?.collegeData?.rank <= 0 ? '-' : data?.collegeData?.rank)
              }}
            </p>
          </div>
        </div>
        <div class="schoolList-people" style="width: 128px">
          <h1>
            {{ data?.collegeData?.planNum
            }}<span style="font-size: 12px">人</span>
          </h1>
          <!-- <div class="schoolList-title">{{data.chooseSubjectText}}</div> -->
        </div>
        <div class="schoolList-grade" style="width: 330px">
          <div class="schoolList-grade-left" style="width: 25%">
            <div class="schoolList-grade-size">录取人数</div>
            <div class="schoolList-grade-size">线差</div>
            <div class="schoolList-grade-size">最低分</div>
            <div class="schoolList-grade-size">最低位次</div>
            <div class="schoolList-grade-size schoolList-grade-size-icon">
              <span>等效位差</span>
              <el-tooltip placement="top">
                <template #content>
                  什么是等效位差？
                  <br />
                  历年等效位差根据考生历年的等效位-历年位次的差值得出，
                  <br />
                  换算后的等效位差可更精准的与历年位次进行比较。
                </template>
                <QuestionFilled style="width: 12px; margin-left: 8px" />
              </el-tooltip>
            </div>
          </div>
          <div
            v-for="(moreItem, index) in data?.collegeData?.moreYear"
            style="width: 25%"
          >
            <div class="schoolList-grade-left">
              <div class="schoolList-grade-size-number alitem">
                {{ moreItem.enterNum }}
              </div>
              <div class="schoolList-grade-size-number alitem">
                {{ moreItem.lineDiff || '-' }}
              </div>
              <div class="schoolList-grade-size-number alitem">
                {{ moreItem.minScore }}
                <div
                  v-if="
                    (moreItem.zjText * 1 > 0 && moreItem.minScore * 1 > 0) ||
                    moreItem.zjText == '有征集'
                  "
                  style="background-color: #fbc7c2; color: red"
                >
                  征
                </div>
              </div>
              <div class="schoolList-grade-size-number alitem">
                {{ moreItem.minRank }}
              </div>
              <div class="schoolList-grade-size-number alitem items">
                <span
                  v-if="
                    moreItem.equivalentBitDifference == '-' ||
                    !moreItem.equivalentBitDifference
                  "
                >
                  -
                </span>
                <span
                  v-else-if="moreItem.equivalentBitDifference < 0"
                  style="color: #ff7d00"
                >
                  低{{
                    moreItem.equivalentBitDifference.toString().substring(1)
                  }}</span
                >
                <span
                  v-else-if="moreItem.equivalentBitDifference >= 0"
                  style="color: #00b56a"
                >
                  高{{ moreItem.equivalentBitDifference }}</span
                >
              </div>
            </div>
          </div>
        </div>
        <div
          style="width: 180px; padding: 40px; cursor: pointer"
          class="cloum alitem center"
        >
          <div class="between" style="width: 53%" v-if="status != 0">
            <el-icon size="20" color="#2990f9">
              <Rank />
            </el-icon>
            <el-popconfirm
              confirm-button-text="删除"
              cancel-button-text="取消"
              icon-color="#626AEF"
              title="确认删除"
              @confirm="onClickDeleteCollege(index)"
            >
              <template #reference>
                <el-icon size="20" color="#2990f9">
                  <Delete />
                </el-icon>
              </template>
            </el-popconfirm>
          </div>

          <div
            style="
              display: flex;
              font-size: 14px;
              margin-top: 15px;
              justify-content: center;
            "
            @click="onClickShowMajors(data.collegeData)"
          >
            专业 {{ data.majorsInfo.length }} &nbsp;
            <el-icon size="20">
              <ArrowDown v-if="!isShowMajors(data.collegeData)" />
              <ArrowUp v-else />
            </el-icon>
          </div>
        </div>
      </div>

      <VueDraggable
        ref="el"
        v-model="data.majorsInfo"
        :animation="150"
        ghostClass="ghost"
        class="flex-col gap-2 p-4 w-300px h-300px m-auto bg-gray-500/5 rounded"
      >
        <div
          v-if="isShowMajors(data.collegeData)"
          style="
            width: 100%;
            background-color: #fafbfe;
            display: flex;
            border-bottom: 1px solid #e5e6eb;
          "
          v-for="(major, idx) in data.majorsInfo"
          :key="major.id"
        >
          <div class="schoolList-sequence"></div>
          <div class="schoolList-Left">
            <!-- <h1>{{ major.chance }}%</h1> -->
            <div v-if="major.isNewly">
              <h1 style="font-size: 24px">新增</h1>
            </div>
            <div v-else>
              <span>
                <span style="font-size: 30px">{{ major.chance }}</span> %</span
              >
              <div class="schoolList-Left-size">
                {{ major.probabilityExplain }}
              </div>
            </div>
          </div>
          <div
            class="schoolList-Center curr"
            style="flex: 1 1 0%"
            @click="handleMajor(major)"
          >
            <div class="schoolName-size">{{ major.professionRealName }}</div>
            <div style="font-size: 12px; margin-left: 20px">
              {{ major.remarkExt }}
            </div>
            <div class="schoolList-size">
              <div>
                代码:
                {{
                  major.professionEnrollCode ? major.professionEnrollCode : '-'
                }}
                <span v-if="!!major.mseLevel"> | </span>
                <span v-if="!!major.mseLevel" class="mseLevel">{{
                  major.mseLevel
                }}</span>
              </div>
            </div>
          </div>
          <div class="schoolList-people" style="width: 128px">
            <div class="schoolList-Number" style="font-size: 30px">
              {{ major.planNum ? major.planNum : '-'
              }}<span style="font-size: 12px">人</span>
            </div>
            <div class="schoolList-title">
              {{
                (major.learnYear ? major.learnYear : '-') +
                '年 ￥' +
                (major.cost ? major.cost : '-')
              }}
            </div>
          </div>
          <div class="schoolList-grade" style="width: 330px">
            <div class="schoolList-grade-left" style="width: 25%">
              <div class="schoolList-grade-size">录取人数</div>
              <div class="schoolList-grade-size">线差</div>
              <div class="schoolList-grade-size">最低分</div>
              <div class="schoolList-grade-size">最低位次</div>
              <div class="schoolList-grade-size schoolList-grade-size-icon">
                <span>等效位差</span>
                <el-tooltip placement="top">
                  <template #content>
                    什么是等效位差？
                    <br />
                    历年等效位差根据考生历年的等效位-历年位次的差值得出，
                    <br />
                    换算后的等效位差可更精准的与历年位次进行比较。
                  </template>
                  <QuestionFilled style="width: 12px; margin-left: 8px" />
                </el-tooltip>
              </div>
            </div>
            <div v-for="(moreItem, index) in major.moreYear" style="width: 25%">
              <div class="schoolList-grade-left">
                <div class="schoolList-grade-size-number alitem">
                  {{ moreItem.enterNum }}
                </div>
                <div class="schoolList-grade-size-number alitem">
                  {{ moreItem.lineDiff || '-' }}
                </div>
                <div class="schoolList-grade-size-number alitem">
                  {{ moreItem.minScore }}
                  <div
                    v-if="
                      (moreItem.zjText * 1 > 0 && moreItem.minScore * 1 > 0) ||
                      moreItem.zjText == '有征集'
                    "
                    style="background-color: #fbc7c2; color: red"
                  >
                    征
                  </div>
                </div>
                <div class="schoolList-grade-size-number alitem">
                  {{ moreItem.minRank }}
                </div>
                <div class="schoolList-grade-size-number alitem items">
                  <span
                    v-if="
                      moreItem.equivalentBitDifference == '-' ||
                      !moreItem.equivalentBitDifference
                    "
                  >
                    -
                  </span>
                  <span
                    v-else-if="moreItem.equivalentBitDifference < 0"
                    style="color: #ff7d00"
                  >
                    低{{
                      moreItem.equivalentBitDifference.toString().substring(1)
                    }}</span
                  >
                  <span
                    v-else-if="moreItem.equivalentBitDifference >= 0"
                    style="color: #00b56a"
                  >
                    高{{ moreItem.equivalentBitDifference }}</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div
            style="width: 180px; padding: 40px; cursor: pointer"
            class="cloum alitem center"
          >
            <div style="width: 53%" class="between" v-if="status != 0">
              <el-icon size="20" color="#2990f9">
                <Rank />
              </el-icon>
              <el-icon
                size="20"
                color="#2990f9"
                @click="onClickDeleteMajor(index, idx)"
              >
                <Delete />
              </el-icon>
            </div>
          </div>
        </div>
      </VueDraggable>
    </div>
  </VueDraggable>
  <Drawertool ref="drawertoolRef" />
</template>
<script setup>
import { VueDraggable } from 'vue-draggable-plus';
import Drawertool from '@/components/Drawertool';
import bus from '@/utils/bus.js';
import { searchMajor } from '@/api/appv2/appv1.js';

import volunteersStore from '@/store/modules/volunteerInfos';
import { ref, watch } from 'vue';
const emits = defineEmits(['changeScInitialLoad']);

const drawertoolRef = ref(null);
const props = defineProps({
  // 是否全部展开/收起
  allUnfold: {
    type: Boolean,
    default: false,
  },
  // 是否显示录取率
  showChancelv: {
    type: Boolean,
    default: true,
  },
  currentSort: {
    type: String,
    default: '',
  },
  studentData: {
    type: Object,
    default: {},
  },
  status: {
    type: Number,
    default: 0,
  },
});

const volunteerStore = volunteersStore();

const volunteerInfos = ref([]);
const storeVolunteerInfos = computed(() => volunteerStore.volunteerInfos);
const keys = ref([]);
const equivalents = ref({});
// 展开查看专业列表的学校ID数组
const showMajorsSchoolIDs = ref([]);

const majorLeavel = ref('');
const fetcSearchMajor = (major) => {
  let data = {
    search: major.professionRealName,
    code: major.majorCode,
  };
  searchMajor(data).then((res) => {
    if (res.code == 20000) {
      majorLeavel.value = res.data[0].level;
      major.level = majorLeavel.value - 1;
      localStorage.setItem('student_id', props.studentData.studentId);
      drawertoolRef.value.handleChangeDrawer(true, '3-1');
      nextTick(() => {
        bus.emit('handleOpenMajorDet', major);
      });
    }
  });
};

// 大学名称点击
const handleScoolNameClick = (data) => {
  localStorage.setItem('student_id', props.studentData.studentId);
  let myData = data.collegeData;
  drawertoolRef.value.handleChangeDrawer(true, '3', myData);
};
// 大学下面的专业名称点击
const handleMajor = (major) => {
  fetcSearchMajor(major);
};
const isInitialLoad = ref(false);

watch(
  () => volunteerInfos.value.map((item) => item.majorsInfo),
  (newValue, oldValue) => {
    if (oldValue.length) {
      isInitialLoad.value = true;
      emits('changeScInitialLoad', isInitialLoad.value);
    }
  }
);

// 监听一键展开收起
watch(
  () => props.allUnfold,
  (newVal) => {
    showMajorsSchoolIDs.value = [];
    if (newVal) {
      for (let key in volunteerInfos.value) {
        let volunteer = volunteerInfos.value[key];
        showMajorsSchoolIDs.value.push(volunteer.collegeData.id);
      }
    }
  }
);

watch(
  () => storeVolunteerInfos.value,
  (newVal) => {
    formatStoreVolunteerInfos(newVal);
  }
);

watch(
  () => props.currentSort,
  () => {
    storeVolunteerInfos.value = volunteerStore.volunteerInfos;
    formatStoreVolunteerInfos(storeVolunteerInfos.value);
  }
);

function formatStoreVolunteerInfos(newVal) {
  if (newVal) {
    let arr = [];
    keys.value = Object.keys(newVal);
    for (let key in newVal) {
      let info = newVal[key];
      info.key = key;
      arr.push(info);
    }
    volunteerInfos.value = arr;

    equivalents.value = JSON.parse(localStorage.getItem('equivalents'));
    if (
      equivalents.value.length > 0 ||
      Object.keys(equivalents.value).length !== 0
    ) {
      for (const v in volunteerInfos.value) {
        if (!!volunteerInfos.value[v].collegeData) {
          for (const vv of volunteerInfos.value[v].collegeData.moreYear) {
            if (equivalents.value[vv.year].eqRank) {
              if (!!vv.minRank && vv.minRank !== 0 && vv.minRank !== '-') {
                // equivalentBitDifference 等效位差
                vv.equivalentBitDifference =
                  vv.minRank - equivalents.value[vv.year].eqRank;
              } else {
                vv.equivalentBitDifference = '-';
              }
            } else {
              vv.equivalentBitDifference = '-';
            }
          }
          for (const vv of volunteerInfos.value[v].majorsInfo) {
            for (const vvv of vv.moreYear) {
              if (equivalents.value[vvv.year].eqRank) {
                if (
                  !!vvv.minRank ||
                  (vvv.minRank !== 0 && vvv.minRank !== '-')
                ) {
                  vvv.equivalentBitDifference =
                    vvv.minRank - equivalents.value[vvv.year].eqRank;
                } else {
                  vvv.equivalentBitDifference = '-';
                }
              } else {
                vvv.equivalentBitDifference = '-';
              }
            }
          }
        }
      }
    }
  }
}

// 拖拽排序结束
function draggableEnd(event) {
  if (event.oldIndex != event.newIndex) {
    volunteerInfos.value.forEach((item, index) => {
      item.key = keys.value[index];
    });

    setVolunteerInfos();
  }
}

function setVolunteerInfos() {
  let infos = {};
  volunteerInfos.value.forEach((item) => {
    infos[item.key] = item;
    delete infos[item.key]['key'];
  });
  volunteerStore.setVolunteerInfos(infos);
}

/**
 * 点击调整志愿表序号
 * @param {String} key 院校键
 * @param {String} keyStr 调整到键
 */
function onClickVolunteerInfoKeysItem(index, idx) {
  if (index != idx) {
    let keyArr = keys.value;
    let moveVolunteer = volunteerInfos.value[index];
    moveVolunteer.key = keys.value[idx];

    if (idx <= index) {
      for (let i = index; i > idx; i--) {
        volunteerInfos.value[i] = volunteerInfos.value[i - 1];
        volunteerInfos.value[i].key = keyArr[i];
      }

      volunteerInfos.value[idx] = moveVolunteer;
    } else {
      for (let i = index; i < idx; i++) {
        volunteerInfos.value[i] = volunteerInfos.value[i + 1];
        volunteerInfos.value[i].key = keyArr[i];
      }

      volunteerInfos.value[idx] = moveVolunteer;
    }

    setVolunteerInfos();
  }
}

// 点击展开收起专业列表
function onClickShowMajors(data) {
  let index = showMajorsSchoolIDs.value.findIndex((item) => item == data.id);
  if (index >= 0) {
    showMajorsSchoolIDs.value.splice(index, 1);
  } else {
    showMajorsSchoolIDs.value.push(data.id);
  }
}

// 是否展开专业列表
function isShowMajors(data) {
  let index = showMajorsSchoolIDs.value.findIndex((item) => item == data.id);
  return index >= 0;
}

// 点击删除填报的院校
function onClickDeleteCollege(index) {
  // let allKey = Object.keys(volunteerInfos.value)

  if (volunteerInfos.value.length == 1) {
    ElMessage({
      message: '请至少保留一个志愿！！！',
      type: 'warning',
    });
    return;
  }

  volunteerInfos.value.splice(index, 1);
  keys.value.splice(keys.value.length - 1, 1);

  volunteerInfos.value.forEach((item, index) => {
    item.key = keys.value[index];
  });

  setVolunteerInfos();
  // 将下面的值分别往上移动 ABCD志愿表 将要删除B 则C到B D到C 最后删除志愿表最后一个数据
  // for (let i = index; i < allKey.length; i++) {
  // 	let k = allKey[i + 1]
  // 	if (k) {
  // 		let key = allKey[i]
  // 		volunteerInfos.value[key] = volunteerInfos.value[k]
  // 	}
  // }

  // 删除最后一个数据
  // delete volunteerInfos.value[allKey[allKey.length - 1]]
  // volunteerStore.setVolunteerInfos(volunteerInfos.value)
}

/**
 * 点击删除填报的院校专业
 * @param String key 志愿表中院校对应字母key A-Z
 * @param Number majorIdx 院校下专业下标
 */
function onClickDeleteMajor(index, majorIdx) {
  if (volunteerInfos.value[index].majorsInfo.length <= 1) {
    ElMessage({
      message: '请至少保留一个专业',
      type: 'warning',
    });
    return;
  }

  volunteerInfos.value[index].majorsInfo.splice(majorIdx, 1);
  setVolunteerInfos();
  // volunteerStore.setVolunteerInfos(volunteerInfos.value)
}
</script>
<style lang="scss" scoped>
.ghost {
  opacity: 0.04;
  background: #000 !important;
}

.schoolList {
  display: flex;
  flex-direction: column;
  border-right: none;
  background: #fff;
  position: relative;
  border-bottom: 1px solid #e5e6eb;

  .schoolList-look-button {
    color: #165dff;
    width: 90px;
    height: 40px;
    background-color: #fff;
    border: 1px solid #165dff;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
  }

  .schoolList-grade {
    display: flex;

    .schoolList-grade-left {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 100%;

      .schoolList-grade-size {
        height: 25%;
        padding: 10px 5px;
        text-align: left;
        font-size: 12px;
        font-weight: 400;
        line-height: 12px;
        border-bottom: 1px solid #f2f3f5;
        border-right: 1px solid #f2f3f5;
      }

      .schoolList-grade-size-number {
        height: 25%;
        padding: 10px 5px;
        text-align: left;
        font-size: 12px;
        font-weight: 400;
        line-height: 12px;
        border-bottom: 1px solid #f2f3f5;
        border-right: 1px solid #f2f3f5;
        padding-left: 10px;
      }

      .schoolList-grade-size-icon {
        align-items: center;
        display: flex;
        flex-direction: row;
      }
    }
  }

  .schoolList-people {
    display: flex;
    flex-direction: column;
    text-align: center;
    padding: 18px 0;
    border-right: 1px solid #e5e6eb;

    .schoolList-Number {
      text-align: center;
      font-size: 20px;
      font-weight: 400;
      color: #1d2129;
      line-height: 24px;
    }

    .schoolList-title {
      font-size: 12px;
      font-weight: 400;
      color: #86909c;
      line-height: 1.5;
    }
  }

  .schoolList-Center {
    min-width: 100px;
    margin-bottom: 10px;

    .schoolName {
      font-size: 18px;
      font-weight: 500;
      color: #1d2129;
      line-height: 27px;
      margin-left: 20px;
      margin-top: 20px;
    }

    .schoolName-size {
      font-size: 14px;
      font-weight: 400;
      color: #1d212c;
      line-height: 27px;
      margin-left: 20px;
      margin-top: 20px;
    }

    .schoolList-size {
      font-size: 12px;
      font-weight: 400;
      color: #86909c;
      line-height: 24px;
      display: flex;
      margin-left: 20px;
      align-items: center;

      .mseLevel {
        background-color: #fbe6e8;
        padding: 2px 4px;
        font-size: 10px;
        color: #f54f4a;
      }
    }

    .schoolList-bottom {
      display: flex;
      margin-left: 20px;
      margin-top: 10px;
      margin-bottom: 10px;

      .schoolList-bottom-size {
        background: #fff;
        border-radius: 2px 2px 2px 2px;
        border: 1px solid #bcc3cc;
        font-size: 12px;
        font-weight: 400;
        color: #86909c;
        padding: 0 4px;
        margin: 0 4px;
      }
    }
  }

  .schoolList-sequence {
    width: 80px;
    padding-left: 40px;
    padding-top: 18px;
    padding-bottom: 18px;
  }

  .schoolList-Left {
    width: 115px;
    padding-left: 40px;
    padding-top: 18px;
    padding-bottom: 18px;
    border-right: 1px solid #f2f3f5;

    .schoolList-Left-chance {
      font-size: 30px;
    }

    .schoolList-Left-size {
      text-align: left;
      font-size: 12px;
      font-family:
        PingFang SC-Regular,
        PingFang SC;
      font-weight: 400;
      color: #86909c;
      line-height: 12px;
      margin-top: 10px;
    }

    .schoolList-Left-number {
      width: 20px;
      height: 20px;
      // background-color: #F53F3F;
      text-align: center;
      line-height: 20px;
      border-radius: 4px;
      color: #fff;
      margin-top: 10px;
    }
  }
}

.chance1 {
  background-color: #f53f3f;
}

.chance2 {
  background-color: #ff8c33;
}

.chance3 {
  background-color: #00bf10;
}
</style>
